const express = require('express');
const jwt = require('jsonwebtoken');
const router = express.Router();
const db = require('../db');

// 登录接口
router.post('/login', (req, res) => {
    const { studentId, password } = req.body;

    const sql = 'SELECT * FROM students WHERE studentId = ? AND password = ?';
    db.query(sql, [studentId, password], (err, results) => {
        if (err) throw err;

        if (results.length === 0) {
            return res.status(401).json({ message: '学号或密码错误' });
        }
        const secretKey = "kio";
        const user = results[0];
        const token = jwt.sign({ id: user.id, studentId: user.studentId }, secretKey, { expiresIn: '2h' });
        res.json({ message: '登录成功', token });
    });
});

// 验证token并获取学生信息
router.get('/studentInfo', (req, res) => {
    const token = req.headers['authorization'];

    if (!token) {
        return res.status(403).json({ message: 'Token缺失' });
    }

    jwt.verify(token, 'kio', (err, decoded) => {
        if (err) {
            return res.status(403).json({ message: 'Token无效' });
        }

        const { studentId } = decoded;
        const sql = 'SELECT * FROM students WHERE studentId = ?';
        db.query(sql, [studentId], (err, results) => {
            if (err) {
                return res.status(500).json({ message: '数据库查询失败' });
            }

            if (results.length === 0) {
                return res.status(404).json({ message: '学生信息未找到' });
            }
            console.log(results[0])
            res.json(results[0]); // 返回学生信息
        });
    });
});

module.exports = router;
